package com.dmall.play.interview.chapter08;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Leetcode46 {

    private List<List<Integer>> ans = new ArrayList<>();
    private boolean[] visited;

    public List<List<Integer>> permute(int[] nums) {
        if (nums == null || nums.length <= 0) {
            return ans;
        }
        visited = new boolean[nums.length];
        Deque<Integer> stack = new ArrayDeque<>();
        generatePermutation(nums, 0, stack);
        return ans;
    }

    private void generatePermutation(int[] nums, int index, Deque<Integer> stack) {
        if (index == nums.length) {
            ans.add(new ArrayList<>(stack));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!visited[i]) {
                stack.addLast(nums[i]);
                visited[i] = true;
                generatePermutation(nums, index + 1, stack);
                stack.removeLast();
                visited[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        Leetcode46 leetcode = new Leetcode46();
        int[] nums = {1, 2, 3};
        System.out.println(leetcode.permute(nums));
    }
}
